package p_400

import com.sun.xml.internal.fastinfoset.util.StringArray
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress

/**
 * UDP echo 协议的客户端
 */
class UDPEchoClient {

    companion object {
        const val port = 7
        fun main(args: StringArray) {
            try {
                val inetAddres = InetAddress.getByName("localhost")
                val socket = DatagramSocket()
                SenderThread(socket, inetAddres, port).apply { start() }
                ReceiveThread(socket).apply { start() }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}


/**
 * 发送流的线程
 */
class SenderThread(val dSocket: DatagramSocket,
                   val inetAddress: InetAddress,
                   val port: Int) : Thread() {

    @Volatile
    var stoped = false

    fun halt() {
        stoped = true
    }

    override fun run() {
//        可填写任意  输入流
        val userInput = BufferedReader(InputStreamReader(System.`in`))
        while (true) {
            if (stoped) return
            val line = userInput.readLine()
            if ("." == line) break
            val datas = line.toByteArray()
            val output = DatagramPacket(datas, datas.size, inetAddress, port)
            dSocket.send(output)
            yield()
        }


    }
}

/**
 * 接受流的线程
 */
class ReceiveThread(val dSocket: DatagramSocket) : Thread() {
    @Volatile
    var stopped = false

    override fun run() {
        val buffer = ByteArray(65507)
        try {
            while (true) {
                if (stopped) return
                val dp = DatagramPacket(buffer, buffer.size)
                dSocket.receive(dp)
                val str = String(dp.data, 0, dp.length)
                println("receive datagrampacket:$str")
                yield()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}